<?php
declare (strict_types=1);

namespace app\blog\controller;
use app\BaseController;
use app\common\upload\UeditorUploaderTool;
use app\common\upload\QiniuUeditorUploaderTool;

class Ueditor extends BaseController
{
   private $config;
   public function initialize()
   {
       /**此处地址注意修改***/
       $config_path='./static/vendor/ueditor1_4_3/php/config.json';
       $this->config = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents($config_path)), true);
       parent::initialize(); // TODO: Change the autogenerated stub
   }
   //获取一个文件上传类
   private function getUploader($fileField, $config,$type){
       if(conf('system','qiniuyun')){
           return new QiniuUeditorUploaderTool($fileField, $config, $type); //图片上传至本地以及七牛云
       }else{
           return new UeditorUploaderTool($fileField, $config, $type);//图片上传至本地
       }
   }

    public function index(){
       $data=$this->request->param();

       if(isset($data['action'])&&$data['action']){
           $result= call_user_func(array($this, $data['action']));
       }else{
           $result=array(
               'state'=> '请求地址出错'
           );
       }
        /* 输出结果 */
        if (isset($data["callback"])) {
            if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
                echo htmlspecialchars($data["callback"]) . '(' . $result . ')';
            } else {
                return json(array(
                    'state'=> 'callback参数不合法'
                ));
            }
        } else {
            return $result;
        }
   }

   private function config(){
       return json($this->config);
   }
    /* 上传图片 */
    private function uploadimage(){
        $config = array(
            "pathFormat" => $this->config['imagePathFormat'],
            "maxSize" => $this->config['imageMaxSize'],
            "allowFiles" => $this->config['imageAllowFiles']
        );
        $fieldName = $this->config['imageFieldName'];
        $base64 = "upload";
        $up = $this->getUploader($fieldName, $config, $base64);

        /**
         * 得到上传文件所对应的各个参数,数组结构
         * array(
         *     "state" => "",          //上传状态，上传成功时必须返回"SUCCESS"
         *     "url" => "",            //返回的地址
         *     "title" => "",          //新文件名
         *     "original" => "",       //原始文件名
         *     "type" => ""            //文件类型
         *     "size" => "",           //文件大小
         * )
         */
        return json($up->getFileInfo());
    }
    /* 上传涂鸦 */
    private function uploadscrawl(){
        $config = array(
            "pathFormat" => $this->config['scrawlPathFormat'],
            "maxSize" => $this->config['scrawlMaxSize'],
            "allowFiles" => $this->config['scrawlAllowFiles'],
            "oriName" => "scrawl.png"
        );
        $fieldName = $this->config['scrawlFieldName'];
        $base64 = "base64";
        $up = $this->getUploader($fieldName, $config, $base64);
        return json($up->getFileInfo());
    }
    /* 上传视频 */
    private function uploadvideo(){
        $config = array(
            "pathFormat" => $this->config['videoPathFormat'],
            "maxSize" => $this->config['videoMaxSize'],
            "allowFiles" => $this->config['videoAllowFiles']
        );
        $fieldName = $this->config['videoFieldName'];
        $base64 = "upload";
        $up = $this->getUploader($fieldName, $config, $base64);
        return json($up->getFileInfo());
    }
    /* 上传文件 */
    private function uploadfile(){
        $config = array(
            "pathFormat" => $this->config['filePathFormat'],
            "maxSize" => $this->config['fileMaxSize'],
            "allowFiles" => $this->config['fileAllowFiles']
        );
        $fieldName = $this->config['fileFieldName'];
        $base64 = "upload";
        $up = $this->getUploader($fieldName, $config, $base64);
        return json($up->getFileInfo());
    }
    /* 列出图片 */
    private function listimage(){
        $allowFiles = $this->config['imageManagerAllowFiles'];
        $listSize = $this->config['imageManagerListSize'];
        $path = $this->config['imageManagerListPath'];
        $allowFiles = substr(str_replace(".", "|", implode("", $allowFiles)), 1);

        /* 获取参数 */
        $get=$this->request->get();
        $size = isset($get['size']) ? $get['size'] : $listSize;
        $start = isset($get['start']) ? $get['start'] : 0;
        $end = $start + $size;

        /* 获取文件列表 */
        $path = $_SERVER['DOCUMENT_ROOT'] . (substr($path, 0, 1) == "/" ? "":"/") . $path;
        $files = $this->getfiles($path, $allowFiles);
        if (!count($files)) {
            return json(array(
                "state" => "no match file",
                "list" => array(),
                "start" => $start,
                "total" => count($files)
            ));
        }
        /* 获取指定范围的列表 */
        $len = count($files);
        for ($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--){
            $list[] = $files[$i];
        }
        /* 返回数据 */
        return json(array(
            "state" => "SUCCESS",
            "list" => $list,
            "start" => $start,
            "total" => count($files)
        ));
    }
    /* 列出文件 */
    private function listfile(){
        $allowFiles = $this->config['fileManagerAllowFiles'];
        $listSize = $this->config['fileManagerListSize'];
        $path = $this->config['fileManagerListPath'];
        $allowFiles = substr(str_replace(".", "|", implode("", $allowFiles)), 1);

        /* 获取参数 */
        $get=$this->request->get();
        $size = isset($get['size']) ? $get['size'] : $listSize;
        $start = isset($get['start']) ? $get['start'] : 0;
        $end = $start + $size;

        /* 获取文件列表 */
        $path = $_SERVER['DOCUMENT_ROOT'] . (substr($path, 0, 1) == "/" ? "":"/") . $path;
        $files = $this->getfiles($path, $allowFiles);
        if (!count($files)) {
            return json(array(
                "state" => "no match file",
                "list" => array(),
                "start" => $start,
                "total" => count($files)
            ));
        }
        /* 获取指定范围的列表 */
        $len = count($files);
        for ($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--){
            $list[] = $files[$i];
        }
        /* 返回数据 */
        return json(array(
            "state" => "SUCCESS",
            "list" => $list,
            "start" => $start,
            "total" => count($files)
        ));
    }
     /**
     * 遍历获取目录下的指定类型的文件
     * @param $path
     * @param array $files
     * @return array
     */
    private function getfiles($path, $allowFiles, &$files = array())
    {
        if (!is_dir($path)) return array();
        if(substr($path, strlen($path) - 1) != '/') $path .= '/';
        $handle = opendir($path);
        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $path2 = $path . $file;
                if (is_dir($path2)) {
                    $this->getfiles($path2, $allowFiles, $files);
                } else {
                    if (preg_match("/\.(".$allowFiles.")$/i", $file)) {
                        $files[] = array(
                            'url'=> substr($path2, strlen($_SERVER['DOCUMENT_ROOT'])),
                            'mtime'=> filemtime($path2)
                        );
                    }
                }
            }
        }
        return $files;
    }

    /* 抓取远程文件 */
    private function catchimage(){
        set_time_limit(0);
        /* 上传配置 */
        $config = array(
            "pathFormat" => $this->config['catcherPathFormat'],
            "maxSize" => $this->config['catcherMaxSize'],
            "allowFiles" => $this->config['catcherAllowFiles'],
            "oriName" => "remote.png"
        );
        $fieldName = $this->config['catcherFieldName'];
        /* 抓取远程图片 */
        $list = array();
        $get=$this->request->get();
        $post=$this->request->post();
        if (isset($post[$fieldName])) {
            $source = $post[$fieldName];
        } else {
            $source = $get[$fieldName];
        }
        foreach ($source as $imgUrl) {
            $item = $this->getUploader($imgUrl, $config, "remote");
            $info = $item->getFileInfo();
            array_push($list, array(
                "state" => $info["state"],
                "url" => $info["url"],
                "size" => $info["size"],
                "title" => htmlspecialchars($info["title"]),
                "original" => htmlspecialchars($info["original"]),
                "source" => htmlspecialchars($imgUrl)
            ));
        }
        /* 返回抓取数据 */
        return json(array(
            'state'=> count($list) ? 'SUCCESS':'ERROR',
            'list'=> $list
        ));
    }

}
